<template>
	<s-layout title="铺货记录" navbar="normal1">
		<!-- 导航栏 -->
    <assNavbar title="铺货记录"></assNavbar>

    <su-fixed top placeholder="">
      <view class="record-top" :style="{top: statusBarHeight  + 'px'}">
        <view 
          class="record-top-item" 
          v-for="(item) in state.tabs" 
          :key="item.record_type"
          :class="{'active': state.activeTab === item.record_type}"
          @tap="handleTabChange(item.record_type)"
        >
          {{ item.name }}({{ item.count }})
        </view>
      </view>
    </su-fixed>

		<!-- 内容 -->
		<view class="distribution-content-box"  >
			<view class="distribution-content">
				<RecordItem 
					v-for="(product, index) in state.products" 
					:key="product.id"
					:product="product"
					@actionUnbind="handleProductUnbind"
				/>
			</view>
		</view>

		<uni-load-more
      v-if="state.pagination.total > 0"
      :status="state.loadStatus"
      :content-text="{
        contentdown: '上拉加载更多',
      }"
      @tap="loadmore"
    />
    <s-empty v-if="state.pagination.total === 0" icon="/static/soldout-empty.png" text="暂无数据"></s-empty>

	</s-layout>
</template>

<script setup>
	import { ref, reactive,onMounted, computed ,getCurrentInstance} from 'vue'
	import {
		onLoad,
		onShow,
		onHide,
		onPageScroll,
		onReachBottom,
		onPullDownRefresh
	} from '@dcloudio/uni-app';
	
	import sheep from '@/sheep';
	import assNavbar from '@/components/ass-navbar.vue';
	import RecordItem from './components/RecordItem.vue';

	const statusBarHeight = sheep.$platform.device.statusBarHeight; // 状态栏高度
	let eventChannel =null
	// 枚举
	const enumType = {
		quick: '快速出单好货',
		hot: '站外爆款热销',
		supplier: '严选供货商',
	}


	const state = reactive({
    activeTab: '',
		type: '', // 类型名称
		pagination: {
      current_page: 1,
      last_page: 1,
      total: 0,
    },
    loadStatus: '', // 加载更多状态 ['more' | 'noMore']

		products: [
			// {
			// 	id: 1,
			// 	time: '2025-04-19 12:00:00',
			// 	title: '暖宝宝暖贴袋鼠保暖贴暖服帖自发热鞋垫暖足贴贴暖宝宝暖贴袋鼠保暖贴暖服帖自发热鞋垫暖足贴贴',
			// 	price: '12.33',
			// 	sales: '1万+',
			// 	category: '家具/架子/置物架',
			// 	isContracted: false,
			// 	status: 1 // 1:在售 2:铺货失败 3:货源已失效
			// },
			
		],
		tabs: [
			{ name: '全部', count: 0, record_type: '' },
			{ name: '铺货成功', count: 0, record_type: 'success' },
			{ name: '铺货失败', count: 0, record_type: 'error' },
			{ name: '货源失效', count: 0, record_type: 'loss' }
		]
	})

	let listParams = reactive({
		record_type: '', // success/error/loss=失效
    page: 1,
    list_rows: 10, // 每页20条数据
  })

	const userInfo = computed(() => sheep.$store('user').userInfo);

	const handleTabChange = (record_type) => {
		console.log('handleTabChange:::', record_type)
		state.activeTab = record_type
		listParams.record_type = record_type
		getListData()
	}

	const resetData = () => {
    state.products = []
    state.pagination = {
      current_page: 1,
      last_page: 1,
      total: 0
    }
    state.loadStatus = ''
  }

	onMounted(()=>{
		 const instance = getCurrentInstance().proxy
		eventChannel = instance.getOpenerEventChannel();
	})
	const getListData = async () => {
		try {
      const { error, data } = await sheep.$api.distribution.distributionRecord(userInfo.value.cyq_store_id, listParams)
      if (error == 0) {
        const { total, current_page, last_page } = data.list
				// tab 头部数量显示
				state.tabs[0].count = data.count.error + data.count.loss + data.count.success
				state.tabs[1].count = data.count.success
				state.tabs[2].count = data.count.error
				state.tabs[3].count = data.count.loss

        if (current_page === 1) {
          state.products = data.list.data;
        } else {
          // 如果是加载更多，则追加数据
          state.products = [...state.products, ...data.list.data]
        }
        

        Object.assign(state.pagination, { total, current_page, last_page })

        if (state.pagination.current_page < state.pagination.last_page) {
          state.loadStatus = 'more';
        } else {
          state.loadStatus = 'noMore';
        }

        return data.list.data
      }
    } catch (error) {
      throw error
    }
	}

	const handleProductUnbind = async (item) => {
		try {
			const { store_id, goods_id } = item
			const params = { store_id, goods_id }
			const { error, msg } = await sheep.$api.distribution.unBindGoods(params)
			eventChannel.emit('cancelRecord', {
			      goods_id: item.father_goods_id
			    });
			getListData()
			uni.showToast({
        title: msg,
        icon: 'none',
      });
		} catch (err) {
			console.log(err)
		}
	}

	const loadmore = () => {
    if (state.loadStatus !== 'noMore') {
      state.pagination.current_page ++ 
      listParams.page ++ 
      getListData();
    }
  }

	onReachBottom(() => {
    console.log('触底了。')
     loadmore()
  });

	onLoad((options) => {
		console.log('onLoad', options)
		state.type = options.type
		getListData();
	})
</script>

<style lang="scss" scoped>
@import './style/record.scss';
</style>

